<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>File Server</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="/index.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <h1>📁 File Server</h1>

    <!-- 导航栏 -->
    <div class="nav-bar">
        <% if (parentPath !== '.') { %>
            <a class="upload-button" href="/?path=<%= encodeURIComponent(parentPath) %>">← 上一级</a>
        <% } %>
        <span class="current-path">当前路径: <%= currentPath %></span>
    </div>

    <!-- 上传表单 -->
    <div class="upload-section">
        <form action="/upload" method="post" enctype="multipart/form-data"  accept-charset="UTF-8">
            <input type="hidden" name="path" value="<%= currentPath %>">
            <div class="upload-button">
                📤 选择文件
                <input type="file" id="file-input" name="files" multiple
                       onchange="this.form.submit()">
            </div>
            <span style="margin-left: 1rem; color: #666;">支持多选文件</span>
        </form>
    </div>

    <!-- 目录列表 -->
    <h3>📂 目录</h3>
    <ul class="directory-list">
        <% directories.forEach(dir => { %>
            <li class="directory-item">
                <a class="directory-link" href="/?path=<%= encodeURIComponent(dir.path) %>">
                    <%= dir.name %>/
                </a>
            </li>
        <% }) %>
    </ul>

    <!-- 文件列表 -->
    <h3>📄 文件</h3>
    <form action="/download" method="post" >
        <input type="hidden" name="path" value="<%= currentPath %>">
        <ul class="file-list">
            <% files.forEach(file => { %>
                <li class="file-item">
                    <input class="file-list-input" type="checkbox" name="files" value="<%= file %>">
                    <a class="file-link" href="/<%= currentPath ? `share/${currentPath}/${file}` : `share/${file}` %>" download>
                        <%= file %>
                    </a>
                </li>
            <% }) %>
        </ul>
        <button type="submit" class="download-button">⬇️ 下载选中</button>
        <button type="button" class="delete-button" onclick="handleDelete()">🗑️ 删除选中</button>
    </form>
</div>
<!-- 修改 views/index.ejs 文件 -->
<script>
  // 更新按钮状态函数
  function updateButtonStates() {
    const checkedCount = getCheckedFiles().length;
    document.querySelector('.download-button').disabled = checkedCount === 0;
    document.querySelector('.delete-button').disabled = checkedCount === 0;
  }
  document.addEventListener('DOMContentLoaded', function() {
    const checkboxes = document.querySelectorAll('input[name="files"]');
    const downloadForm = document.querySelector('form[action="/download"]');
    // 处理表单提交
    downloadForm.addEventListener('submit', function(e) {
      e.preventDefault();
      const checkedFiles = Array.from(checkboxes)
          .filter(cb => cb.checked)
          .map(cb => cb.value);

      if (checkedFiles.length === 1) {
        // 单个文件直接下载
        const currentPath = '<%= currentPath %>';
        const filePath = currentPath ?
            `${currentPath}/${checkedFiles[0]}` :
            checkedFiles[0];
        window.location.href = `/download/single?path=${encodeURIComponent(filePath)}`;
      } else {
        // 多个文件提交表单
        this.submit();
      }
    });

    // 初始化状态
    updateButtonStates();

    // 监听所有复选框变化
    checkboxes.forEach(cb => {
      cb.addEventListener('change', updateButtonStates);
    });
  });
  // 通用获取选中文件方法
  function getCheckedFiles() {
    return Array.from(document.querySelectorAll('input[name="files"]:checked'))
        .map(cb => cb.value);
  }
  function showNotification(message, type) {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;

    document.body.appendChild(notification);
    setTimeout(() => notification.remove(), 5000);
  }
  // 新增删除处理函数
  // function handleDelete() {
  //   const checkedFiles = getCheckedFiles();
  //
  //   if (checkedFiles.length === 0) return;
  //
  //   if (confirm(`确定要永久删除这 ${checkedFiles.length} 个文件吗？\n此操作无法撤销！`)) {
  //     const form = document.getElementById('deleteForm');
  //     const input = document.createElement('input');
  //     input.type = 'hidden';
  //     input.name = 'files';
  //     input.value = JSON.stringify(checkedFiles);
  //     form.appendChild(input);
  //     form.submit();
  //   }
  // }
  async function handleDelete() {
    const checkedFiles = getCheckedFiles();
    if (checkedFiles.length === 0) return;

    if (!confirm(`确定要删除选中的 ${checkedFiles.length} 个文件吗？`)) return;

    const deleteBtn = document.querySelector('.delete-button');
    const originalText = deleteBtn.innerHTML;

    try {
      deleteBtn.innerHTML = '<div class="spinner"></div> 删除中...';
      deleteBtn.disabled = true;

      const response = await fetch('/delete', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          files: JSON.stringify(checkedFiles),
          path: '<%= currentPath %>'
        })
      });
      if (response.ok) {
        showNotification('删除成功', 'success');
      } else {
        showNotification('删除失败' ,'error');
      }
    } catch (err) {
      showNotification('删除失败: ' + err.message, 'error');
    } finally {
      deleteBtn.innerHTML = originalText;
      deleteBtn.disabled = false;
      setTimeout(() => location.reload(), 1000); // 1秒后刷新
    }
  }
</script>
</body>
</html>